// @algorithm @lc id=59 lang=cpp 
// @title spiral-matrix-ii


#define print(...)
// @test(3)=[[1,2,3],[8,9,4],[7,6,5]]
// @test(1)=[[1]]
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> mat(n, vector<int>(n));
        int left = 0, right = n,
            up = 0, dn = n;
        int v = 0;
        while(true){
            for(int i=left; i<right; i++)
                mat[up][i] = ++v;
            print("up=", up, "\n", Mat(mat))
            if(++up>=dn) break;

            for(int i=up; i<dn; i++)
                mat[i][right-1] = ++v;
            print("right=", right, "\n", Mat(mat))
            if(--right<=left) break;

            for(int i=right-1; i>=left;i--)
                mat[dn-1][i] = ++v;
            print("dn=", dn, "\n", Mat(mat))
            if(--dn<=up) break;

            for(int i=dn-1; i>=up; i--)
                mat[i][left] = ++v;
            print("left=", left, "\n", Mat(mat))
            if(++left>=right) break;
        }
        return mat;
    }
};